import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios';
import token from './token';

const isProd = import.meta.env.PROD;
const baseURL: string = <string>import.meta.env.VITE_APP_API_BASE_URL;

const instance = axios.create({
    baseURL: baseURL,
    timeout: 6000, // 请求超时时间
});

instance.interceptors.request.use((request: AxiosRequestConfig) => {
    const t = token.get()
    if (t) {
        request.headers['Authorization'] = `Bearer ${t}`;
    }
    if (!isProd) {
        console.debug('Request:', request);
    }
    return request;
});


instance.interceptors.response.use((response: AxiosResponse) => {
    if (!isProd) {
        console.debug('Response:', response.data);
    }
    return response;
});

const request = async (method: Method, url: string, options?: AxiosRequestConfig) => {
    try {
        const response = await instance.request({
            method: method,
            url: url,
            ...options
        })
        return response.data;
    } catch (err) {
        console.log(err)
    }
}

export default {
    get(url: string, config?: AxiosRequestConfig) {
        return request('get', url, config)
    },
    put(url: string, data: any, config?: AxiosRequestConfig) {
        return request('put', url, { data: data, ...config })
    },
    post(url: string, data: any, config?: AxiosRequestConfig) {
        return request('post', url, { data: data, ...config })
    },
};
